/* atoi example */
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */
//将字符串转化为数字
//跳过不可见字符，在遇到数字或者负号时开始转化
//在字符串中读取到非数字时停止
//字符串代表的值超过int时，返回的值不确定
#include <string.h>
#include <ctype.h>

int my_atoi(const char* str)
{
    int sum = 0;
    int flag = 0;
    while(isspace(*str))
    {
        str++;
    }
    if(*str == '-')
    {
        flag = 1;
        str++;
    }
    while(*str >= '0'&&*str <= '9')
    {
        sum *= 10;
        sum += *str - '0';
        str++;
    }
    if(flag)
    return -1 * sum;
    else
    return sum;
}

int main ()
{
    int i;
    char buffer[256];
    printf ("Enter a number: ");
    fgets (buffer, 256, stdin);
    i = my_atoi(buffer);
    printf ("The value entered is %d. Its double is %d.\n",i,i*2);
    return 0;
}